package com.angus.modules.content.service.impl;

import cn.hutool.json.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.angus.common.security.config.AlipayConfig;
import com.angus.modules.content.domain.SysOrder;
import com.angus.modules.content.dto.OrderPayDto;
import com.angus.modules.content.repository.SysOrderRepository;
import com.angus.modules.content.service.AlipayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author liyanan
 * @date 2024/12/17 2:23 PM
 * @description
 */
@Service
@Slf4j
public class AlipayServiceImpl implements AlipayService {
    @Resource
    private AlipayConfig aliPayConfig;
    private static final String FORMAT = "JSON";
    private static final String CHARSET = "UTF-8";
    private static final String SIGN_TYPE = "RSA2";

    @Autowired
    private SysOrderRepository sysOrderRepository;
    @Override
    public String pay(OrderPayDto dto,Long userId) {

        SysOrder order = sysOrderRepository.getOrderByOrderNo(dto.getOrderNo(), userId);
        if(Objects.isNull(order)){
            return "订单不存在";
        }
        // 1. 创建Client，通用SDK提供的Client，负责调用支付宝的API
        AlipayClient alipayClient = new DefaultAlipayClient(aliPayConfig.getGatewayUrl(), aliPayConfig.getAppId(),
                aliPayConfig.getAppPrivateKey(), FORMAT, CHARSET, aliPayConfig.getAlipayPublicKey(), SIGN_TYPE);

        // 2. 创建 Request并设置Request参数
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setNotifyUrl(aliPayConfig.getNotifyUrl());
        JSONObject bizContent = new JSONObject();
        bizContent.set("out_trade_no", dto.getOrderNo());  // 我们生成的订单编号
        bizContent.set("total_amount", order.getCourseAmount()); // 订单的总金额
        bizContent.set("subject", order.getCourseName());   // 支付的名称
//        if (PayType.PC.getTypeFlag().equals(dto.getPayType())){
//            // 设置产品码
//            bizContent.set("product_code", "FAST_INSTANT_TRADE_PAY");  // 固定配置
//        }
//        if (PayType.PHONE.getTypeFlag().equals(dto.getPayType())){
//            bizContent.set("product_code", "QUICK_WAP_WAY");  // 固定配置
//        }
        // 设置订单绝对超时时间
        bizContent.set("time_expire",order.getCreateTime().plusDays(1)
                .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        request.setBizContent(bizContent.toString());
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return form;
    }

    @Override
    public String queryPay(OrderPayDto dto, Long userId) {

        SysOrder order = sysOrderRepository.getOrderByOrderNo(dto.getOrderNo(), userId);
        if(Objects.isNull(order)){
            return "订单不存在";
        }
        // 初始化SDK
        AlipayClient alipayClient = new DefaultAlipayClient(aliPayConfig.getGatewayUrl(), aliPayConfig.getAppId(),
                aliPayConfig.getAppPrivateKey(), FORMAT, CHARSET, aliPayConfig.getAlipayPublicKey(), SIGN_TYPE);

        // 构造请求参数以调用接口
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.set("out_trade_no", dto.getOrderNo());  // 我们生成的订单编号
        // 设置查询选项
        List<String> queryOptions = new ArrayList<String>();
        queryOptions.add("trade_settle_info");
        bizContent.set("query_options", queryOptions);
        request.setBizContent(bizContent.toString());
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return form;
    }

}
